﻿@page "/authentication/login"
@inherits BasePage
@inject IOptions<ServerSettings> ServerSettings
@inject MessageService MessageService
@inject AccessTokenProvider AccessTokenProvider

<PageContainer Title="Login" PageTitle="@Title">
    <Breadcrumb>
        <Breadcrumb>
            <BreadcrumbItem>
                <a href="">
                    <MdiIcon Type="@IconNames.Home" />
                    <span>Home</span>
                </a>
            </BreadcrumbItem>
            <BreadcrumbItem>
                <span>
                    <MdiIcon Type="@IconNames.Login" />
                    <span>Login</span>
                </span>
            </BreadcrumbItem>
        </Breadcrumb>
    </Breadcrumb>
    <ChildContent>
        <Form Model="@model"
              OnFinish="OnLogin">
            <FormItem Label="User Name">
                <Input @bind-Value="@context.Username" />
            </FormItem>
            <FormItem Label="Password">
                <InputPassword @bind-Value="@context.Password" />
            </FormItem>
            <FormItem>
                <Button Type="@ButtonType.Primary" HtmlType="submit">
                    Login
                </Button>
            </FormItem>
        </Form>
    </ChildContent>
</PageContainer>

@code{
    class Model
    {
        [Required]
        public string Username { get; set; }
        [Required]
        public string Password { get; set; }
    }

    private Model model = new Model();

    protected override void OnInitialized()
    {
        Title = "Login";
        base.OnInitialized();
    }

    async Task OnLogin()
    {
        try
        {
            var token = await Service.UserService.Login(new Services.Models.UserLoginRequest
            {
                UserName = model.Username,
                Password = model.Password,
            });
            if (!string.IsNullOrWhiteSpace(token))
            {
                await AccessTokenProvider.SetToken(token);
                Service.Context.Token = token;
                var user = await Service.UserService.GetCurrent()!;
                _ = MessageService.Success($"Welcome {user.NickName}");
                NavigationManager.NavigateTo("/");
            }
            else
            {
                await MessageService.Error($"Failed to log in.");
            }
        }
        catch
        {
            await MessageService.Error($"Failed to log in.");
        }
    }
}